{% extends "base.html" %}

{% block title %}图书馆座位预约{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-book"></i> 图书馆座位预约</h2>
                <div>
                    <a href="{{ url_for('dashboard') }}" class="btn btn-outline-primary">
                        <i class="fas fa-home"></i> 返回主页
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 时间查询功能 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-search"></i> 按时间查询座位状态
                    </h5>
                </div>
                <div class="card-body">
                    <form id="timeQueryForm" class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="queryDate">查询日期</label>
                                <input type="date" class="form-control" id="queryDate" name="queryDate" aria-describedby="queryDateHelp">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="queryStartTime">开始时间</label>
                                <select class="form-control" id="queryStartTime" name="queryStartTime" aria-describedby="queryStartTimeHelp">
                                    <option value="">全天</option>
                                    <option value="08:00">08:00</option>
                                    <option value="09:00">09:00</option>
                                    <option value="10:00">10:00</option>
                                    <option value="11:00">11:00</option>
                                    <option value="12:00">12:00</option>
                                    <option value="13:00">13:00</option>
                                    <option value="14:00">14:00</option>
                                    <option value="15:00">15:00</option>
                                    <option value="16:00">16:00</option>
                                    <option value="17:00">17:00</option>
                                    <option value="18:00">18:00</option>
                                    <option value="19:00">19:00</option>
                                    <option value="20:00">20:00</option>
                                    <option value="21:00">21:00</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="queryEndTime">结束时间</label>
                                <select class="form-control" id="queryEndTime" name="queryEndTime" aria-describedby="queryEndTimeHelp">
                                    <option value="">全天</option>
                                    <option value="09:00">09:00</option>
                                    <option value="10:00">10:00</option>
                                    <option value="11:00">11:00</option>
                                    <option value="12:00">12:00</option>
                                    <option value="13:00">13:00</option>
                                    <option value="14:00">14:00</option>
                                    <option value="15:00">15:00</option>
                                    <option value="16:00">16:00</option>
                                    <option value="17:00">17:00</option>
                                    <option value="18:00">18:00</option>
                                    <option value="19:00">19:00</option>
                                    <option value="20:00">20:00</option>
                                    <option value="21:00">21:00</option>
                                    <option value="22:00">22:00</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <div>
                                    <button type="button" class="btn btn-primary" onclick="querySeatsWithTime()">
                                        <i class="fas fa-search"></i> 查询
                                    </button>
                                    <button type="button" class="btn btn-secondary ml-2" onclick="resetQuery()">
                                        <i class="fas fa-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 楼层导航 -->
    <div class="row mb-4">
        <div class="col-12">
            <ul class="nav nav-pills justify-content-center" id="floor-tabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="floor1-tab" data-bs-toggle="pill" data-bs-target="#floor1" type="button" role="tab">
                        <i class="fas fa-building"></i> 一楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor2-tab" data-bs-toggle="pill" data-bs-target="#floor2" type="button" role="tab">
                        <i class="fas fa-building"></i> 二楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor3-tab" data-bs-toggle="pill" data-bs-target="#floor3" type="button" role="tab">
                        <i class="fas fa-building"></i> 三楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor4-tab" data-bs-toggle="pill" data-bs-target="#floor4" type="button" role="tab">
                        <i class="fas fa-building"></i> 四楼
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="floor5-tab" data-bs-toggle="pill" data-bs-target="#floor5" type="button" role="tab">
                        <i class="fas fa-building"></i> 五楼
                    </button>
                </li>
            </ul>
        </div>
    </div>

    <!-- 座位状态说明 -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body py-2">
                    <div class="d-flex justify-content-center align-items-center" role="legend" aria-label="座位状态图例">
                        <span class="mr-4">
                            <span class="seat-indicator available" aria-hidden="true"></span>
                            <small>空闲</small>
                        </span>
                        <span class="mr-4">
                            <span class="seat-indicator occupied" aria-hidden="true"></span>
                            <small>已预约</small>
                        </span>
                        <span>
                            <span class="seat-indicator my-reservation" aria-hidden="true"></span>
                            <small>我的预约</small>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 座位布局 -->
    <div class="tab-content" id="floor-content">
        {% for floor in [1, 2, 3] %}
        <div class="tab-pane fade {% if floor == 1 %}show active{% endif %}" id="floor{{ floor }}" role="tabpanel">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-map-marker-alt"></i> {{ floor }}楼座位布局
                    </h5>
                </div>
                <div class="card-body">
                    <div class="seat-grid">
                        {% for seat in seats %}
                            {% if seat.floor == floor %}
                            <div class="seat-item">
                                {% if seat.student_id %}
                                    {% if seat.student_id == session.user_id %}
                                    <!-- 我的预约 -->
                                    <button class="btn seat-btn my-reservation" 
                                            onclick="showSeatOptions('{{ seat.id }}', '{{ seat.seat_number|e }}', 'my')"
                                            title="点击管理预约">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% else %}
                                    <!-- 已被预约 -->
                                    <button class="btn seat-btn occupied" 
                                            onclick="showSeatOptions('{{ seat.id }}', '{{ seat.seat_number|e }}', 'occupied')"
                                            title="点击查看详情">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% endif %}
                                {% else %}
                                <!-- 空闲座位 -->
                                <button class="btn seat-btn available" 
                                        onclick="showReservationCard('{{ seat.id }}', '{{ seat.seat_number|e }}')"
                                        title="点击预约座位">
                                    <div class="seat-number">{{ seat.seat_number }}</div>
                                    <div class="seat-status">空闲</div>
                                </button>
                                {% endif %}
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
        <!-- 4楼座位布局 -->
        <div class="tab-pane fade" id="floor4" role="tabpanel">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-map-marker-alt"></i> 4楼座位布局
                    </h5>
                </div>
                <div class="card-body">
                    <div class="seat-grid">
                        {% for seat in seats %}
                            {% if seat.floor == 4 %}
                            <div class="seat-item">
                                {% if seat.student_id %}
                                    {% if seat.student_id == session.user_id %}
                                    <!-- 我的预约 -->
                                    <button class="btn seat-btn my-reservation" 
                                            onclick="cancelReservation('{{ seat.id }}', '{{ seat.seat_number|e }}')"
                                            title="点击取消预约">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% else %}
                                    <!-- 已被预约 -->
                                    <button class="btn seat-btn occupied" 
                                            onclick="showReservedMessage()"
                                            title="座位已被预约">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% endif %}
                                {% else %}
                                <!-- 空闲座位 -->
                                <button class="btn seat-btn available" 
                                        onclick="showReservationModal('{{ seat.id }}', '{{ seat.seat_number|e }}')"
                                        title="点击预约座位">
                                    <div class="seat-number">{{ seat.seat_number }}</div>
                                    <div class="seat-status">空闲</div>
                                </button>
                                {% endif %}
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
        <!-- 5楼座位布局 -->
        <div class="tab-pane fade" id="floor5" role="tabpanel">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-map-marker-alt"></i> 5楼座位布局
                    </h5>
                </div>
                <div class="card-body">
                    <div class="seat-grid">
                        {% for seat in seats %}
                            {% if seat.floor == 5 %}
                            <div class="seat-item">
                                {% if seat.student_id %}
                                    {% if seat.student_id == session.user_id %}
                                    <!-- 我的预约 -->
                                    <button class="btn seat-btn my-reservation" 
                                            onclick="cancelReservation('{{seat.id}}','{{ seat.seat_number }}')"
                                            title="点击取消预约">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% else %}
                                    <!-- 已被预约 -->
                                    <button class="btn seat-btn occupied" 
                                            onclick="showReservedMessage()"
                                            title="座位已被预约">
                                        <div class="seat-number">{{ seat.seat_number }}</div>
                                        <div class="seat-user">{{ seat.name }}</div>
                                        <div class="seat-time">{{ seat.start_time.strftime('%H:%M') if seat.start_time else '' }}</div>
                                    </button>
                                    {% endif %}
                                {% else %}
                                <!-- 空闲座位 -->
                                <button class="btn seat-btn available" 
                                        onclick="showReservationCard('{{ seat.id }}', '{{ seat.seat_number }}')"
                                        title="点击预约座位">
                                    <div class="seat-number">{{ seat.seat_number }}</div>
                                    <div class="seat-status">空闲</div>
                                </button>
                                {% endif %}
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
</div>

<!-- 确认对话框 -->
<div class="modal fade" id="confirmModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="confirmModalTitle">确认操作</h5>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="confirmModalBody">
                <!-- 动态内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmBtn">确认</button>
            </div>
        </div>
    </div>
</div>

<!-- 预约模态框 -->
<div class="modal fade" id="reservationModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">预约座位</h5>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="reservationForm">
                    <div class="form-group">
                        <label>座位号：</label>
                        <span id="selectedSeat" class="font-weight-bold"></span>
                    </div>
                    <div class="form-group">
                        <label for="reservationDate">预约日期：</label>
                        <input type="date" class="form-control" id="reservationDate" name="reservationDate" required aria-describedby="reservationDateHelp">
                    </div>
                    <div class="form-group">
                        <label for="startTime">开始时间：</label>
                        <select class="form-control" id="startTime" name="startTime" required aria-describedby="startTimeHelp">
                            <option value="">请选择开始时间</option>
                            <option value="08:00">08:00</option>
                            <option value="09:00">09:00</option>
                            <option value="10:00">10:00</option>
                            <option value="11:00">11:00</option>
                            <option value="12:00">12:00</option>
                            <option value="13:00">13:00</option>
                            <option value="14:00">14:00</option>
                            <option value="15:00">15:00</option>
                            <option value="16:00">16:00</option>
                            <option value="17:00">17:00</option>
                            <option value="18:00">18:00</option>
                            <option value="19:00">19:00</option>
                            <option value="20:00">20:00</option>
                            <option value="21:00">21:00</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="endTime">结束时间：</label>
                        <select class="form-control" id="endTime" name="endTime" required aria-describedby="endTimeHelp">
                            <option value="">请选择结束时间</option>
                            <option value="09:00">09:00</option>
                            <option value="10:00">10:00</option>
                            <option value="11:00">11:00</option>
                            <option value="12:00">12:00</option>
                            <option value="13:00">13:00</option>
                            <option value="14:00">14:00</option>
                            <option value="15:00">15:00</option>
                            <option value="16:00">16:00</option>
                            <option value="17:00">17:00</option>
                            <option value="18:00">18:00</option>
                            <option value="19:00">19:00</option>
                            <option value="20:00">20:00</option>
                            <option value="21:00">21:00</option>
                            <option value="22:00">22:00</option>
                        </select>
                    </div>
                    <input type="hidden" id="seatId" name="seatId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitReservation()">确认预约</button>
            </div>
        </div>
    </div>
</div>

<!-- 消息提示模态框 -->
<div class="modal fade" id="messageModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示</h5>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p id="messageText"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<style>
.seat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 15px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 10px;
}

.seat-item {
    display: flex;
    justify-content: center;
}

.seat-btn {
    width: 100px;
    height: 80px;
    border-radius: 10px;
    border: 2px solid;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.seat-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.seat-btn:focus {
    outline: 2px solid #007bff;
}

/* 预约小卡片样式 */
.seat-info-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    border-radius: 15px;
    margin-bottom: 15px;
}

.seat-number-display {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
}

.seat-status-display {
    font-size: 14px;
    opacity: 0.9;
}

/* 时间段选择样式 */
.time-slots-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
    max-height: 400px;
    overflow-y: auto;
}

.time-slot-btn {
    padding: 12px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
}

.time-slot-btn:hover {
    border-color: #007bff;
    background: #f8f9fa;
}

.time-slot-btn.selected {
    border-color: #007bff;
    background: #007bff;
    color: white;
}

.time-slot-btn.unavailable {
    background: #f8f9fa;
    color: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
}

.time-slot-btn.unavailable:hover {
    border-color: #e9ecef;
    background: #f8f9fa;
}

.time-slot-time {
    font-weight: bold;
    font-size: 16px;
}

.time-slot-duration {
    font-size: 12px;
    opacity: 0.8;
    margin-top: 2px;
}

/* 修复模态框层级问题 */
#reservationCardModal {
    z-index: 1060;
}

#reservationCardModal .modal-dialog {
    z-index: 1061;
}

#timeSlotModal {
    z-index: 1070;
}

#timeSlotModal .modal-dialog {
    z-index: 1071;
}

.modal-backdrop {
    z-index: 1050;
}

.form-control:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

.btn:focus {
    outline: 2px solid #007bff;
    outline-offset: 2px;
}

.seat-btn.available {
    background: #d4edda;
    border-color: #28a745;
    color: #155724;
}

.seat-btn.available:hover {
    background: #c3e6cb;
    color: #155724;
}

.seat-btn.occupied {
    background: #f8d7da;
    border-color: #dc3545;
    color: #721c24;
    cursor: not-allowed;
}

.seat-btn.my-reservation {
    background: #fff3cd;
    border-color: #ffc107;
    color: #856404;
}

.seat-btn.my-reservation:hover {
    background: #ffeaa7;
    color: #856404;
}

.seat-number {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 2px;
}

.seat-user {
    font-size: 10px;
    color: #666;
    margin-bottom: 1px;
}

.seat-time {
    font-size: 9px;
    color: #888;
}

.seat-status {
    font-size: 11px;
    color: #666;
}

.seat-indicator {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 4px;
    margin-right: 5px;
    border: 1px solid #ddd;
}

.seat-indicator.available {
    background: #d4edda;
    border-color: #28a745;
}

.seat-indicator.occupied {
    background: #f8d7da;
    border-color: #dc3545;
}

.seat-indicator.my-reservation {
    background: #fff3cd;
    border-color: #ffc107;
}

.nav-pills .nav-link {
    border-radius: 25px;
    margin: 0 5px;
    transition: all 0.3s ease;
}

.nav-pills .nav-link.active {
    background: linear-gradient(45deg, #007bff, #0056b3);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,123,255,0.3);
}

.card {
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-radius: 15px;
}

.card-header {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    border-bottom: 1px solid #dee2e6;
    border-radius: 15px 15px 0 0 !important;
}

@media (max-width: 768px) {
    .seat-grid {
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
        gap: 10px;
        padding: 15px;
    }
    
    .seat-btn {
        width: 80px;
        height: 60px;
        font-size: 10px;
    }
    
    .seat-number {
        font-size: 12px;
    }
}
</style>

<script>
// 显示预约模态框
function showReservationModal(seatId, seatNumber) {
    if (!seatId || !seatNumber) {
        console.error('Invalid seat parameters');
        return;
    }
    document.getElementById('seatId').value = seatId;
    document.getElementById('selectedSeat').textContent = seatNumber;
    
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('reservationDate').value = today;
    document.getElementById('reservationDate').min = today;
    
    const reservationModal = new bootstrap.Modal(document.getElementById('reservationModal'));
    reservationModal.show();
}

// 显示已预约消息
function showReservedMessage() {
    document.getElementById('messageText').textContent = '此座位已被预约，请选择别的位置';
    const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
    messageModal.show();
}

// 显示使用中消息
function showInUseMessage() {
    document.getElementById('messageText').textContent = '此座位正在被使用';
    const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
    messageModal.show();
}

// 显示预约小卡片
function showReservationCard(seatId, seatNumber) {
    if (!seatId || !seatNumber) {
        console.error('Invalid seat parameters');
        return;
    }
    
    // 设置座位信息
    document.getElementById('cardSeatNumber').textContent = seatNumber;
    document.getElementById('cardSeatInfo').textContent = `座位 ${seatNumber}`;
    
    // 存储座位信息供后续使用
    window.currentSeatId = seatId;
    window.currentSeatNumber = seatNumber;
    
    // 使用无backdrop的模态框
    const reservationCardModal = new bootstrap.Modal(document.getElementById('reservationCardModal'), {
        backdrop: false,
        keyboard: true
    });
    reservationCardModal.show();
}

// 显示时间段选择
function showTimeSlotSelection() {
    // 隐藏预约小卡片
    const reservationCardModal = bootstrap.Modal.getInstance(document.getElementById('reservationCardModal'));
    if (reservationCardModal) {
        reservationCardModal.hide();
    }
    
    // 设置座位信息
    document.getElementById('timeSlotSeatNumber').textContent = window.currentSeatNumber;
    
    // 生成时间段
    generateTimeSlots();
    
    // 显示时间段选择模态框
    const timeSlotModal = new bootstrap.Modal(document.getElementById('timeSlotModal'), {
        backdrop: false,
        keyboard: true
    });
    timeSlotModal.show();
}

// 生成时间段选择
function generateTimeSlots() {
    const container = document.getElementById('timeSlotsContainer');
    container.innerHTML = '';
    
    // 从6:00到22:00，每2小时一个时间段
    const timeSlots = [
        { start: '06:00', end: '08:00' },
        { start: '08:00', end: '10:00' },
        { start: '10:00', end: '12:00' },
        { start: '12:00', end: '14:00' },
        { start: '14:00', end: '16:00' },
        { start: '16:00', end: '18:00' },
        { start: '18:00', end: '20:00' },
        { start: '20:00', end: '22:00' }
    ];
    
    timeSlots.forEach((slot, index) => {
        const slotDiv = document.createElement('div');
        slotDiv.className = 'time-slot-btn';
        slotDiv.onclick = () => selectTimeSlot(slotDiv, slot);
        
        slotDiv.innerHTML = `
            <div class="time-slot-time">${slot.start} - ${slot.end}</div>
            <div class="time-slot-duration">2小时</div>
        `;
        
        container.appendChild(slotDiv);
    });
}

// 选择时间段
function selectTimeSlot(element, slot) {
    // 移除其他选中状态
    document.querySelectorAll('.time-slot-btn').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // 添加选中状态
    element.classList.add('selected');
    
    // 存储选中的时间段
    window.selectedTimeSlot = slot;
    
    // 启用确认按钮
    document.getElementById('confirmReservationBtn').disabled = false;
}

// 确认时间段预约
function confirmTimeSlotReservation() {
    if (!window.selectedTimeSlot || !window.currentSeatId) {
        alert('请选择时间段');
        return;
    }
    
    const today = new Date().toISOString().split('T')[0];
    const reservationData = {
        seat_id: window.currentSeatId,
        date: today,
        start_time: window.selectedTimeSlot.start,
        end_time: window.selectedTimeSlot.end
    };
    
    // 发送预约请求
    fetch('/reserve_seat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(reservationData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('预约成功！');
            // 隐藏模态框
            const timeSlotModal = bootstrap.Modal.getInstance(document.getElementById('timeSlotModal'));
            if (timeSlotModal) {
                timeSlotModal.hide();
            }
            // 刷新页面
            location.reload();
        } else {
            alert('预约失败：' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('预约失败，请稍后重试');
    });
}

// 提交预约
function submitReservation() {
    const seatId = document.getElementById('seatId').value;
    const date = document.getElementById('reservationDate').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    
    if (!date || !startTime || !endTime) {
        alert('请填写完整的预约信息');
        return;
    }
    
    if (startTime >= endTime) {
        alert('结束时间必须晚于开始时间');
        return;
    }
    
    // 发送预约请求
    fetch('/reserve_seat_with_time', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            seat_id: parseInt(seatId),
            date: date,
            start_time: startTime,
            end_time: endTime
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const reservationModal = bootstrap.Modal.getInstance(document.getElementById('reservationModal'));
            if (reservationModal) reservationModal.hide();
            location.reload();
        } else {
            alert(data.message || '预约失败，请重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('预约失败，请重试');
    });
}

// 取消预约
function cancelReservation(seatId, seatNumber) {
    if (!seatId || !seatNumber) {
        console.error('Invalid cancellation parameters');
        return;
    }
    if (confirm(`确定要取消座位 ${seatNumber} 的预约吗？`)) {
        fetch(`/cancel_reservation/${parseInt(seatId)}`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message || '取消失败，请重试');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('取消失败，请重试');
        });
    }
}

// 时间选择联动
document.getElementById('startTime').addEventListener('change', function() {
    const startTime = this.value;
    const endTimeSelect = document.getElementById('endTime');
    const endOptions = endTimeSelect.options;
    
    // 重置结束时间选项
    for (let i = 0; i < endOptions.length; i++) {
        endOptions[i].disabled = false;
    }
    
    // 禁用早于或等于开始时间的选项
    if (startTime) {
        for (let i = 0; i < endOptions.length; i++) {
            if (endOptions[i].value && endOptions[i].value <= startTime) {
                endOptions[i].disabled = true;
            }
        }
        endTimeSelect.value = '';
    }
});

// 页面加载时设置默认日期
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('queryDate').value = today;
    document.getElementById('queryDate').min = today;
});

// 按时间查询座位状态
function querySeatsWithTime() {
    const date = document.getElementById('queryDate').value;
    const startTime = document.getElementById('queryStartTime').value;
    const endTime = document.getElementById('queryEndTime').value;
    
    if (!date) {
        alert('请选择查询日期');
        return;
    }
    
    if ((startTime && !endTime) || (!startTime && endTime)) {
        alert('请同时选择开始时间和结束时间，或都不选择查看全天');
        return;
    }
    
    if (startTime && endTime && startTime >= endTime) {
        alert('结束时间必须晚于开始时间');
        return;
    }
    
    // 构建查询URL
    let url = `/library?date=${date}`;
    if (startTime && endTime) {
        url += `&start_time=${startTime}&end_time=${endTime}`;
    }
    
    window.location.href = url;
}

// 重置查询
function resetQuery() {
    window.location.href = '/library';
}

// 显示座位操作选项
function showSeatOptions(seatId, seatNumber, type) {
    if (!seatId || !seatNumber || !type) {
        console.error('Invalid seat options parameters');
        return;
    }
    const modal = document.getElementById('seatOptionsModal');
    const seatInfo = document.getElementById('selectedSeatInfo');
    const actionButtons = document.getElementById('seatActionButtons');
    
    seatInfo.textContent = `座位 ${seatNumber}`;
    
    // 清空之前的按钮
    while (actionButtons.firstChild) {
        actionButtons.removeChild(actionButtons.firstChild);
    }
    
    if (type === 'available') {
        // 空闲座位 - 显示预约按钮
        const reserveBtn = document.createElement('button');
        reserveBtn.className = 'btn btn-success btn-lg mb-2';
        reserveBtn.innerHTML = '<i class="fas fa-calendar-plus"></i> 预约座位';
        reserveBtn.onclick = function() {
            showReservationModal(seatId, seatNumber);
            bootstrap.Modal.getInstance(document.getElementById('seatOptionsModal')).hide();
        };
        
        const br1 = document.createElement('br');
        
        const manageBtn = document.createElement('button');
        manageBtn.className = 'btn btn-info';
        manageBtn.innerHTML = '<i class="fas fa-cog"></i> 座位管理';
        manageBtn.onclick = function() {
            goToSeatManagement(seatId);
            bootstrap.Modal.getInstance(document.getElementById('seatOptionsModal')).hide();
        };
        
        actionButtons.appendChild(reserveBtn);
        actionButtons.appendChild(br1);
        actionButtons.appendChild(manageBtn);
    } else if (type === 'my') {
        // 我的预约 - 显示取消和管理按钮
        const cancelBtn = document.createElement('button');
        cancelBtn.className = 'btn btn-warning btn-lg mb-2';
        cancelBtn.innerHTML = '<i class="fas fa-times"></i> 取消预约';
        cancelBtn.onclick = function() {
            cancelReservation(seatId, seatNumber);
            bootstrap.Modal.getInstance(document.getElementById('seatOptionsModal')).hide();
        };
        
        const br2 = document.createElement('br');
        
        const manageBtn2 = document.createElement('button');
        manageBtn2.className = 'btn btn-info';
        manageBtn2.innerHTML = '<i class="fas fa-cog"></i> 座位管理';
        manageBtn2.onclick = function() {
            goToSeatManagement(seatId);
            bootstrap.Modal.getInstance(document.getElementById('seatOptionsModal')).hide();
        };
        
        actionButtons.appendChild(cancelBtn);
        actionButtons.appendChild(br2);
        actionButtons.appendChild(manageBtn2);
    } else if (type === 'occupied') {
        // 已被预约 - 只显示查看详情
        const viewBtn = document.createElement('button');
        viewBtn.className = 'btn btn-info';
        viewBtn.innerHTML = '<i class="fas fa-eye"></i> 查看详情';
        viewBtn.onclick = function() {
            goToSeatManagement(seatId);
            bootstrap.Modal.getInstance(document.getElementById('seatOptionsModal')).hide();
        };
        
        actionButtons.appendChild(viewBtn);
    }
    
    const seatOptionsModal = new bootstrap.Modal(document.getElementById('seatOptionsModal'));
    seatOptionsModal.show();
}

// 显示已预约消息
function showReservedMessage() {
    document.getElementById('messageText').textContent = '此座位已被预约，请选择别的位置';
    const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
    messageModal.show();
}

// 显示使用中消息
function showInUseMessage() {
    document.getElementById('messageText').textContent = '此座位正在被使用';
    const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
    messageModal.show();
}

// 跳转到座位管理页面
function goToSeatManagement(seatId) {
    if (!seatId) {
        console.error('Invalid seat ID');
        return;
    }
    window.location.href = `/seat_management/${parseInt(seatId)}`;
}

// 关闭预约小卡片模态框
function closeReservationCard() {
    const reservationCardModal = bootstrap.Modal.getInstance(document.getElementById('reservationCardModal'));
    if (reservationCardModal) {
        reservationCardModal.hide();
    }
}

// 关闭时间段选择模态框
function closeTimeSlotModal() {
    const timeSlotModal = bootstrap.Modal.getInstance(document.getElementById('timeSlotModal'));
    if (timeSlotModal) {
        timeSlotModal.hide();
    }
}

// 关闭预约小卡片模态框
function closeReservationCard() {
    const reservationCardModal = bootstrap.Modal.getInstance(document.getElementById('reservationCardModal'));
    if (reservationCardModal) {
        reservationCardModal.hide();
    }
}

// 关闭时间段选择模态框
function closeTimeSlotModal() {
    const timeSlotModal = bootstrap.Modal.getInstance(document.getElementById('timeSlotModal'));
    if (timeSlotModal) {
        timeSlotModal.hide();
    }
}

</script>

<!-- 预约小卡片模态框 -->
<div class="modal fade" id="reservationCardModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-chair"></i> <span id="cardSeatInfo">座位预约</span>
                </h5>
                <button type="button" class="close" onclick="closeReservationCard()">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <div class="seat-info-card">
                    <div class="seat-number-display" id="cardSeatNumber">1F-01</div>
                    <div class="seat-status-display">空闲</div>
                </div>
                <button type="button" class="btn btn-primary btn-lg mt-3" onclick="showTimeSlotSelection()">
                    <i class="fas fa-calendar-plus"></i> 预约座位
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 时间段选择模态框 -->
<div class="modal fade" id="timeSlotModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-clock"></i> 选择预约时间段
                </h5>
                <button type="button" class="close" onclick="closeTimeSlotModal()">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="seat-info mb-3">
                    <strong>座位：</strong><span id="timeSlotSeatNumber">1F-01</span>
                </div>
                <div class="time-slots-grid" id="timeSlotsContainer">
                    <!-- 时间段将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-primary" onclick="confirmTimeSlotReservation()" disabled id="confirmReservationBtn">
                    <i class="fas fa-check"></i> 确认预约
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 座位操作选项模态框 -->
<div class="modal fade" id="seatOptionsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-chair"></i> <span id="selectedSeatInfo">座位操作</span>
                </h5>
                <button type="button" class="close" data-bs-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <p class="mb-3">请选择要执行的操作：</p>
                <div id="seatActionButtons">
                    <!-- 动态生成的按钮将显示在这里 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> 关闭
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}